<?php

// Namespace

namespace Snsfg;


// Dependencies

require_once(PATH_APPLICATION . 'Class/ISocialNetworkDriver.php');

require_once(PATH_APPLICATION . 'Component/Tencent/Tweibo/Tencent.php');

require_once(PATH_APPLICATION . 'Model/CAccount.php');
require_once(PATH_APPLICATION . 'Model/CPostStatus.php');


/**
 * CTencentweiboDriver allows to run and use the social network driver for PHP
 * This class is the implementation of the interface ISocialNetworkDriver
 *
 * @package		Gt_Sync
 * @category	Driver
 */

class CTweiboDriver implements ISocialNetworkDriver
{


	/**
	 *
	 */

	public function closeConnection(&$account)
	{
		e(
			EXCEPTION_SOCIAL_NETWORK_API_NOT_SUPPORTED
		);
	}


	/**
	 *
	 */

	public function completeConnection(&$account)
	{
		$code = fv('code', true);

		$redirect_uri = url('api/json/Account.completeConnection');

		try 
		{
			/**
			* the format of the oauth info from tweibo like: 
			*	array(4) { ["access_token"]=> string(32) "2.00kDVswCQJfBpCf3b2d782530gHlYq" 
			*	["expires_in"]=> int(86400) ["remind_in"]=> string(5) "24602" ["uid"]=> string(10) "2702282260" }
			*/

			$TencentOAuth = new \OAuth();
			$TencentOAuth->init
			(
				pref('[Snsfg]/socialNetwork/tweibo/appid'),
				pref('[Snsfg]/socialNetwork/tweibo/apikey')
			);

			$response = $TencentOAuth->getAccessToken($code, $redirect_uri);
			parse_str($response, $oauthInfo);
		}
		catch (OAuthException $e) {

		}

		// Get and store the personal information

		$tencent = $this->connectDriver
							(
									array
									(
										'openid' => $oauthInfo['openid'],
										'privateApiToken' => $oauthInfo['access_token']
									)
								);

		$userInfo = $tencent->api('user/info');

		// Try to get the social network account

		$account->loadAccount('internalId', $userInfo->data['openid'], SOCIAL_NETWORK_WEIBO);
		$account->setPrivateApiToken($oauthInfo['access_token']);
		$account->setInternalId($oauthInfo['openid']);
		$account->setScreenName($userInfo['screen_name']);
		$account->setAvatar($userInfo['profile_image_url']);
		$account->setFollowersCount($userInfo['followers_count']);
		$account->setFriendsCount($userInfo['friends_count']);
		$account->setTimeOfExpirationOfApiToken($oauthInfo['remind_in'] + time());

	}


	/**
	 *
	 */

	public function connectDriver($params = null)
	{
		$tencent = new \Tencent
		(
			pref('[Snsfg]/socialNetwork/tweibo/appid'),
			$params['openid'],
			$params['privateApiToken']
		);

		return $tencent;
	}


	/**
	 *
	 */

	public function disconnect(&$account)
	{
	}


	/**
	 *
	 */

	public function getUrlClicks(&$account, $shortUrl)
	{
		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $tencent->get_url_clicks($shortUrl);

		return $result;
	}


	/**
	 *
	 */

	public function getUrlReferers(&$account, $shortUrl)
	{
		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $tencent->get_url_referers($shortUrl);

		return $result;
	}


	/**
	 *
	 */

	public function getUrlLocations(&$account, $shortUrl)
	{
		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $tencent->get_url_locations($shortUrl);

		return $result;
	}


	/**
	 *
	 */

	public function grabComments(&$account, $statusFlag)
	{

		$nbComments = pref('[Snsfg]/api/grabComments/nbComments');

		$tencent = $this->connectDriver
								(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$comment = new CComment();

		$rawStatuses = $account->getStatuses($statusFlag);

		foreach ($rawStatuses as $rawStatus) {

			$comment->reset();
			
			$statusId = $rawStatus['internalId'];
			
			$lastComment = $comment->getLast($statusId);

			$page = 0;

			while( !isset($rawComments) || count($rawComments['comments'])>0 )
			{
				$page++;

				$rawComments = $tencent->get_comments_by_sid
				(
					$statusId,
					$page,
					$nbComments,
					$lastComment['internalId'],
					0,
					0
				);

				if(!empty($rawComments['comments']))
				{
					foreach($rawComments['comments'] as $rawComment)
					{
						$comment->reset();

						$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

						if(preg_match_all($preg, $rawComment['text'],$shortUrlRaws)) {
							$shortUrlStr = implode(',', $shortUrlRaws[0]);
							$comment->setShortUrl($shortUrlStr);
						}

						$comment->setAccountId($rawComment['user']['idstr']);
						$comment->setStatusId($rawComment['status']['idstr']);
						$comment->setContent($rawComment['text']);
						$comment->setInternalId($rawComment['idstr']);
						$comment->setCreatedAt(strtotime($rawComment['created_at']));
						$comment->setSocialNetwork($account->getSocialNetwork());
						$comment->save();
					}
				}
			}
			unset($rawComments);
		}
	}


	/**
	 *
	 */	

	public function grabMessages(&$account)
	{

		$nbMessages = pref('[Snsfg]/api/grabMessages/nbMessages');

		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$message = new CMessage();

		$accountId = $account->getInternalId();
		$lastMessage = $message->getLast($accountId);
		
		$page = 0;

		while( !isset($rawMessages) || count($rawMessages['statuses'])>0 )
		{
			$page++;
			
			$rawMessages = $tencent->user_timeline_by_id
			(
				$accountId, 
				$page,
				$nbMessages, 
				$lastMessage['internalId'],
				0, 
				1
			);

			if(!empty($rawMessages['statuses']))
			{
				foreach($rawMessages['statuses'] as $rawMessage)
				{
					$message->reset();

					$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

					if(preg_match_all($preg, $rawMessage['text'],$shortUrlRaws)) {
						$shortUrlStr = implode(',', $shortUrlRaws[0]);
						$message->setShortUrl($shortUrlStr);
					}

					$message->setAccountId($rawMessage['user']['id']);
					$message->setContent($rawMessage['text']);
					$message->setInternalId(number_format($rawMessage['id'], 0, '', ''));
					$message->setRepostsCount($rawMessage['reposts_count']);
					$message->setCommentsCount($rawMessage['comments_count']);
					$message->setCreatedAt(strtotime($rawMessage['created_at']));
					$message->setSocialNetwork($account->getSocialNetwork());
					$message->save();
				}
			}
		}
	}


	/**
	 *
	 */

	public function postStatus(&$account, $messageData)
	{
		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);
		
		$postStatus = new CPostStatus();

		if('on' == $messageData['addPic']) 
		{
			$result = $tencent->upload($messageData['content'], $messageData['tmp_name']);

			if(is_uploaded_file($messageData['tmp_name']))
			{
				$pathToUploadFile = PATH_TEMPORARY . $account->getInternalId() . $account->getReference() . md5($messageData['tmp_name']) . $messageData['picture_name'];
				copy( $messageData['tmp_name'], $pathToUploadFile );

				$postStatus->setPicture($pathToUploadFile);
			}
		}
		else
		{
			$result = $tencent->update($messageData['content']);
		}

		$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

		if(preg_match_all($preg, $result['text'],$shortUrlRaws)) {
			$shortUrlStr = implode(',', $shortUrlRaws[0]);
			$postStatus->setShortUrl($shortUrlStr);
		}

		$postStatus->setAccountId($result['user']['id']);
		$postStatus->setContent($result['text']);
		$postStatus->setInternalId(number_format($result['id'], 0, '', ''));
		$postStatus->setRepostsCount(0);
		$postStatus->setCommentsCount(0);
		$postStatus->setCreatedAt(strtotime($result['created_at']));
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->save();

	}


	/**
	 *
	 */
	 	
	public function startConnection(&$account)
	{

		$TencentOAuth = new \OAuth();
		$TencentOAuth->init
		(
			pref('[Snsfg]/socialNetwork/tweibo/appid'),
			pref('[Snsfg]/socialNetwork/tweibo/apikey')
		);

		v('SESSION::accountId', $account->getId());
		v('SESSION::accountReference', $account->getReference());

		$authorizeUrl = $TencentOAuth->getAuthorizeURL
		(
			url('api/json/Account.completeConnection')
		);
		
		return $authorizeUrl;
	}


	/**
	 *
	 */

	public function updateAccount(&$account) {

	}

	/**
	 *
	 */

	public function updateStatus(&$account) {

	}


	/**
	 *
	 */

	public function updateStatuses(&$account, $statusFlag) {

 		$rawStatuses = $account->getStatuses($statusFlag);

		switch ($statusFlag) {
			case 'post':

				$tencent = $this->connectDriver
								(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);
				
				$status = new CPostStatus();

				foreach ($rawStatuses as $rawStatus) {
					$status->reset();
					$status->loadSecure($rawStatus['id'], $rawStatus['reference']);

					$newStatusRow = $tencent->show_status($rawStatus['internalId']);

					$status->setRepostsCount($newStatusRow['reposts_count']);
					$status->setCommentsCount($newStatusRow['comments_count']);
					$status->save();
				}

				break;
			
			case 'all':

				$status = new CMessage();

				foreach($rawStatuses as $rawStatus) {
					$status->reset();
					$status->loadSecure($rawStatus['id'], $rawStatus['reference']);
					$status->delete();
				}

				$result = $this->grabMessages($account);

				break;
			default:
				// error
				break;
		}

	}


	/**
	 *
	 */

	public function urlCommentCounts(&$account, $shortUrl) {

		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);
		$result = $tencent->url_comment_counts($shortUrl);

		return $result;

	}


	/**
	 *
	 */

	public function urlExpand(&$account, $shortUrl) {

		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $tencent->url_expand($shortUrl);

		return $result;

	}


	/**
	 *
	 */

	public function urlShareCounts(&$account, $shortUrl) {

		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);
		$result = $tencent->url_share_counts($shortUrl);

		return $result;

	}


	/**
	 *
	 */

	public function urlShorten(&$account, $longUrl) {

		$tencent = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$result = $tencent->url_shorten($longUrl);

		return $result;

	}


	/**
	 *
	 */

	public function userLogout(&$account) {

		$tencent = $this->connectDriver
							(
								array
								(
									'privateApiToken' => $account->getPrivateApiToken()
								)
							);

		$result = $tencent->user_logout();

		return $result;

	}


	/**
	 *
	 */

	public function userTimeline(&$account) {

		$tencent = $this->connectDriver
							(
								array
								(
									'privateApiToken' => $account->getPrivateApiToken()
								)
							);
		
		$result = $tencent->user_timeline_by_id();

		return $result;
	}

	public function test(&$account) {
		$tencent = $this->connectDriver
							(
								array
								(
									'privateApiToken' => $account->getPrivateApiToken()
								)
							);
		$result = $tencent->get_uid();

		return $result;
	}
}

?>
